package com.xrtn.service.impl;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.jxcell.CellException;
import com.jxcell.View;
import com.xrtn.bean.*;
import com.xrtn.mapper.*;
import com.xrtn.service.UploadFileService;
import com.xrtn.utils.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class UploadFileServiceImpl implements UploadFileService {


	/**文件存放目录*/
	private String IMG_PRJ_PATH = "/image/";
	/**临时文件存放目录*/
	private String IMG_PRJ_PATH_TMP = "/image/image_tmp/";
	/**临时剪裁文件存放目录*/
	private String IMG_PRJ_PATH_CROP = "/image/crop/";
	/**临时文件存放目录*/
	private String DIR_TMP = "temp"; 
	private int INT_SCALE = 2;

	@Autowired
    private TBookingInfoMapper bookingInfoMapper;
	@Autowired
    private TPatientInfoMapper patientInfoMapper;
    @Autowired
    private TPatientInitMapper patientInitMapper;
	@Autowired
    private TPatientTreatmentMapper patientTreatmentMapper;
    @Autowired
    private TUserInfoMapper userInfoMapper;
    @Autowired
    private SysRoleInfoMapper roleInfoMapper;
    @Autowired
    private SysUserInfoMapper sysUserInfoMapper;
    @Autowired
    private AccountUserInfoMapper accountUserInfoMapper;
	/**
	* @Title: uploadImageToServer 
	* @Description: 上传文件到服务器
	* @param @param imageFile
	* @param @param request
	* @param @return    
	* @return Map<String,Object>     
	* @throws
	 */
	@Override
	public Map<String, Object> uploadImageToServer(MultipartFile imageFile, HttpServletRequest request) {
		//创建携参Map
		Map<String, Object> params = new HashMap<String, Object>();
		try {
			//获取请求路径头
			String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort(); 
			
			//获取文件路径
			String filePath = getFilePath(request, IMG_PRJ_PATH_TMP);
			
			//获取文件名
			String fileName = imageFile.getOriginalFilename();
			//赋值
			fileName = 
					String.format("%s_%s", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()), 
							new Random().nextInt(10000))+fileName.substring(fileName.lastIndexOf("."));
			
			//创建文件
			File targetFile = new File(filePath ,fileName);
			//如果目录不存在
			if (!targetFile.exists()) {
				//那么创建
				targetFile.mkdirs();
			}
			
			// 保存到服务器物理磁盘
			try {
				imageFile.transferTo(targetFile);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			BufferedImage img = ImageIO.read(targetFile);
			// croppic 需要的属性
			params.put("status", "success");
			params.put("url",  basePath+IMG_PRJ_PATH_TMP +fileName);
			params.put("width", img.getWidth());
			params.put("height", img.getHeight());
			System.out.println("imageUrl = " + basePath+IMG_PRJ_PATH_TMP +fileName);
		
		}catch (Exception e) {
			e.printStackTrace();
			params.put("status", "error");
			params.put("message", "your error message text");
		}
		//返回
		return params;
	}

    @Override
    public Map<String,Object> uploadAliOSS(InputStream imageFile, String imageName, HttpServletRequest request,Map<String,Object> params) {

        try{
            // 创建ClientConfiguration实例，按照您的需要修改默认参数。
            ClientConfiguration conf = new ClientConfiguration();
            // 开启支持CNAME选项。
            conf.setSupportCname(true);
            //初始化OSSClient
            OSSClient ossClient= AliyunOSSClientUtil.getOSSClient(conf);

            imageName =
                    String.format("%s_%s", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()),
                            new Random().nextInt(10000))+imageName.substring(imageName.lastIndexOf("."));
            String filePath = AliyunOSSClientUtil.uploadObject2OSS(ossClient, imageFile, imageName, OSSClientConstants.BACKET_NAME, OSSClientConstants.FOLDER);

            ossClient.shutdown();

            params.put("status", "success");
            params.put("url",  filePath);
        }catch (Exception e){
            params.put("status", "error");
            params.put("message", "your error message text");
        }


        return params;
    }


    /**
	* @Title: webImgCrop 
	* @Description: 上传文件
	* @param @param imgUrl
	* @param @param imgW
	* @param @param imgH
	* @param @param imgX1
	* @param @param imgY1
	* @param @param cropW
	* @param @param cropH
	* @param @param request
	* @param @return    
	* @return Map<String,Object>     
	* @throws
	 */
	public Map<String, Object> webImgCrop(String imgUrl,double imgW,double imgH,Integer imgX1,Integer imgY1,Integer cropW,Integer cropH,HttpServletRequest request){
		//创建返回Map
		Map<String, Object> map=new HashMap<String, Object>();
		try {
			//获取请求路径开端
			String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
			//声明变量
			String filePath = "user/";

			CropImage image = new CropImage((int)imgW * INT_SCALE, (int)imgH * INT_SCALE, imgX1 * INT_SCALE, imgY1 *INT_SCALE, cropW * INT_SCALE, cropH * INT_SCALE);
			
			String IMG_URL = "";
			String subPath = "";//要保存的文件本地路径
			String url = "";//照片网络路径
			if(imgUrl.indexOf(IMG_PRJ_PATH_TMP) != -1){ //上传新照片
				IMG_URL = imgUrl.split(IMG_PRJ_PATH_TMP)[1];
				imgUrl = getFilePath(request, IMG_PRJ_PATH_TMP) + IMG_URL;
			} else if(imgUrl.indexOf(IMG_PRJ_PATH_CROP) != -1){ //修改上传到image/crop下的照片
				IMG_URL = imgUrl.split(IMG_PRJ_PATH_CROP)[1];
				imgUrl = getFilePath(request, IMG_PRJ_PATH_CROP) + IMG_URL;
			} else { // 修改上传到image/activityId/brideId下的照片
				IMG_URL = imgUrl.split(IMG_PRJ_PATH)[1];
				imgUrl = getFilePath(request, IMG_PRJ_PATH) + IMG_URL;
				IMG_URL = IMG_URL.indexOf("/"+ DIR_TMP +"/") != -1? IMG_URL.split(DIR_TMP +"/")[1]: IMG_URL.replace(filePath, "");
			}

            subPath = getFilePath(request, IMG_PRJ_PATH) + filePath + IMG_URL;
			url = IMG_PRJ_PATH + filePath + IMG_URL; //照片网络路径
			url = url.replace("//", "/");
			
			image.setSrcPath(imgUrl);
			image.setSubPath(subPath);
			image.cut();
			if(!subPath.equals(imgUrl)){
				this.deleteFile(imgUrl);
			}
			map.put("status", "success");
			map.put("url", basePath + url);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("status", "error");
			map.put("message", "your error message text");
		}
		return map;
	}

    @Override
    public void exportBookingList(HttpServletRequest request, HttpServletResponse response, Map<String, Object> params) {

        SysUserInfo userInfo = (SysUserInfo) request.getSession().getAttribute(HttpUtils.CURRENT_USER_4_POJO);

        //校验当前用户是否有全部门店
        boolean isExport = false, isAll = false;
        if(ObjUtils.isNotEmpty(userInfo.getUserId())){
            SysUserInfo sysUserInfo = sysUserInfoMapper.selectByPrimaryKey(userInfo.getUserId());
            List<Map<String,Object>> userFunctionList= roleInfoMapper.selectRoleLists(sysUserInfo.getUserRole());

            List<String> groupList = new ArrayList<>();

            for (Map<String,Object> functionMap : userFunctionList){
                groupList.add(functionMap.get("menuName").toString());
                if(Integer.parseInt(functionMap.get("functionId").toString()) == 67){
                    isExport = true;
                }
                if(Integer.parseInt(functionMap.get("functionId").toString()) == 45){
                    isAll = true;
                }
            }
        }
        if(isExport){
            if(ObjUtils.isEmpty(params.get("subclinicId"))){
                if(isAll){
                    params.put("subclinicId", null);
                }else{
                    params.put("subclinicId", params.get("subclinicId"));
                }
            }

            List<Map<String,Object>> bookingList = bookingInfoMapper.selectBookingExcelList(params);

            //加密
            View m_view = new View();
            try {
                m_view.setNumSheets(2);

                m_view.setSheet(0);
                m_view.setSheetName(0,"汇总记录表");
                m_view.setSheetName(1,"预约详情表");

                Integer waitCount = 0 ,receptionCount = 0 ,completeCount = 0 ,cancelCount = 0;

                for(int j = 1; j < bookingList.size() ; j++){
                    Integer bookingStatus = Integer.parseInt(bookingList.get(j).get("bookingStatus").toString());
                    if(bookingStatus == 0){
                        //待就诊
                        waitCount++;
                    }
                    if(bookingStatus == 6 || bookingStatus == 2 || bookingStatus == 3){
                        //已到店  调理中  待支付
                        receptionCount++;
                    }
                    if(bookingStatus == 4){
                        //已完成
                        completeCount++;
                    }
                    if(bookingStatus == 5){
                        //取消
                        cancelCount++;
                    }
                }

                m_view.setTextAsValue(0, 0, "总预约量");
                m_view.setTextAsValue(0, 1, String.valueOf(bookingList.size()));
                m_view.setTextAsValue(0, 2, "待就诊");
                m_view.setTextAsValue(0, 3, String.valueOf(waitCount));
                m_view.setTextAsValue(0, 4, "已到店");
                m_view.setTextAsValue(0, 5, String.valueOf(receptionCount));
                m_view.setTextAsValue(0, 6, "已完成");
                m_view.setTextAsValue(0, 7, String.valueOf(completeCount));
                m_view.setTextAsValue(0, 8, "取消");
                m_view.setTextAsValue(0, 9, String.valueOf(cancelCount));

                m_view.setSheet(1);

                m_view.setTextAsValue(0, 0, "预约患者");
                m_view.setTextAsValue(0, 1, "预约门店");
                m_view.setTextAsValue(0, 2, "预约大夫");
//                m_view.setTextAsValue(0, 3, "预约类型");
                m_view.setTextAsValue(0, 3, "到店时间");
//                m_view.setTextAsValue(0, 4, "来源");
                m_view.setTextAsValue(0, 4, "备注");

                for(int j = 1; j <= bookingList.size() ; j++){
                    Object patientName = bookingList.get(j - 1).get("patientName");
                    Object subclinicName = bookingList.get(j - 1).get("subclinicName");
                    Object doctorName = bookingList.get(j - 1).get("doctorName");
//                        Object isFirst = bookingList.get(j - 1).get("isFirst");
                    Object bookingTime = bookingList.get(j - 1).get("bookingTime");
                    Object bookingSource = bookingList.get(j - 1).get("bookingSource");
                    Object bookingDesc = bookingList.get(j - 1).get("bookingDesc");
                    m_view.setText(j, 0, String.valueOf(patientName));
                    m_view.setText(j, 1, String.valueOf(subclinicName));
                    m_view.setText(j, 2, String.valueOf(doctorName));
//                        m_view.setText(j, 3, String.valueOf(isFirst));
                    m_view.setText(j, 3, String.valueOf(bookingTime));
//                        m_view.setText(j, 4, String.valueOf(bookingSource));
                    m_view.setText(j, 4, String.valueOf(bookingDesc));
                }
                try{
                    m_view.write("/usr/local/tomcat-test/admin-tomcat/webapps/image/预约详情记录表.xls", "Gyt12345.");
//                    m_view.write("/Users/pingping/workspace/预约详情记录表.xls");
                }catch (Exception e){
                    e.printStackTrace();
                }
                ExcelTool.download("/usr/local/tomcat-test/admin-tomcat/webapps/image/预约详情记录表.xls", response);
//                ExcelTool.download("/Users/pingping/workspace/患者信息表.xls", response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        //非加密
//        String[] rowsName = new String[] {"预约患者","预约门店","预约大夫","预约类型","到店时间","来源","备注"};
//        List<Object[]> dataList = new ArrayList<Object[]>();
//
//        for (int i = 0 ; i < bookingList.size(); i++ ){
//            Object patientName = bookingList.get(i).get("patientName");
//            Object subclinicName = bookingList.get(i).get("subclinicName");
//            Object doctorName = bookingList.get(i).get("doctorName");
//            Object isFirst = bookingList.get(i).get("isFirst");
//            Object bookingTime = bookingList.get(i).get("bookingTime");
//            Object bookingSource = bookingList.get(i).get("bookingSource");
//            Object bookingDesc = bookingList.get(i).get("bookingDesc");
//            Object[] objs = new Object[rowsName.length];
//            objs[0] = patientName;
//            objs[1] = subclinicName;
//            objs[2] = doctorName;
//            objs[3] = isFirst;
//            objs[4] = bookingTime;
//            objs[5] = bookingSource;
//            objs[6] = bookingDesc;
//            dataList.add(objs);
//        }
//        String fileName = "userDetail";
//        //执行导出
//        ExcelTool.exportExcel(request,response,fileName, rowsName, dataList, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 导出患者列表
     *
     * @param request
     * @param response
     * @param params
     */
    @Override
    public void exportPatientList(HttpServletRequest request, HttpServletResponse response, Map<String, Object> params) {

        SysUserInfo userInfo = (SysUserInfo) request.getSession().getAttribute(HttpUtils.CURRENT_USER_4_POJO);

        //校验当前用户是否有全部门店
        boolean isExport = false, isAll = false;
        if(ObjUtils.isNotEmpty(userInfo.getUserId())){
            SysUserInfo sysUserInfo = sysUserInfoMapper.selectByPrimaryKey(userInfo.getUserId());
            List<Map<String,Object>> userFunctionList= roleInfoMapper.selectRoleLists(sysUserInfo.getUserRole());

            List<String> groupList = new ArrayList<>();

            for (Map<String,Object> functionMap : userFunctionList){
                groupList.add(functionMap.get("menuName").toString());
                if(Integer.parseInt(functionMap.get("functionId").toString()) == 66){
                    isExport = true;
                }
                if(Integer.parseInt(functionMap.get("functionId").toString()) == 45){
                    isAll = true;
                }
            }
        }
        if(isExport){
            if(ObjUtils.isEmpty(params.get("subclinicId"))){
                if(isAll){
                    params.put("subclinicId", null);
                }else{
                    params.put("subclinicId", params.get("subclinicId"));
                }
            }
            List<TPatientInfo> patientList = patientInfoMapper.selectBySubclinicId(params);

            //加密
            View m_view = new View();
            try {
                //{"患者姓名","出生年月","性别","手机号","身高","体重","地址","备注","添加时间"};
                m_view.setTextAsValue(0, 0, "患者姓名");
                m_view.setTextAsValue(0, 1, "出生年月");
                m_view.setTextAsValue(0, 2, "性别");
                m_view.setTextAsValue(0, 3, "手机号");
                m_view.setTextAsValue(0, 4, "身高");
                m_view.setTextAsValue(0, 5, "体重");
                m_view.setTextAsValue(0, 6, "地址");
                m_view.setTextAsValue(0, 7, "备注");
                m_view.setTextAsValue(0, 8, "添加时间");

                for(int j = 1; j <= patientList.size() ; j++){
                    m_view.setText(j, 0, patientList.get(j - 1).getPatientName());
                    m_view.setText(j, 1, patientList.get(j - 1).getPatientBirthday());
                    m_view.setText(j, 2, String.valueOf(patientList.get(j - 1).getPatientGender() == null ? "" : patientList.get(j - 1).getPatientGender() == 0 ? "男" : "女"));
                    m_view.setText(j, 3, patientList.get(j - 1).getPatientPhone());
                    m_view.setText(j, 4, String.valueOf(patientList.get(j - 1).getPatientHeight()));
                    m_view.setText(j, 5, String.valueOf(patientList.get(j - 1).getPatientBodyWeight()));
                    m_view.setText(j, 6, patientList.get(j - 1).getPatientAddress());
                    m_view.setText(j, 7, patientList.get(j - 1).getPatientDesc());
                    m_view.setText(j, 8, String.valueOf(DateUtils.format(patientList.get(j - 1).getCreateTime(),DateUtils.YYYY_MM_DD_HH_MM_SS)));

                }

                //m_view.editCopyRight();
                try{
                    m_view.write("/usr/local/tomcat-test/admin-tomcat/webapps/image/患者信息表.xls", "Gyt12345.");
//                    m_view.write("/Users/pingping/workspace/患者信息表.xls");
                }catch (Exception e){
                    e.printStackTrace();
                }
                ExcelTool.download("/usr/local/tomcat-test/admin-tomcat/webapps/image/患者信息表.xls", response);
//                ExcelTool.download("/Users/pingping/workspace/患者信息表.xls", response);
            } catch (CellException e) {
                e.printStackTrace();
            }
        }


        //非加密
//        String[] rowsName = new String[] {"患者姓名","出生年月","性别","手机号","身高","体重","地址","备注","添加时间"};
//        List<Object[]> dataList = new ArrayList<Object[]>();
//        for (TPatientInfo patientInfo : patientList){
//            Object[] objs = new Object[rowsName.length];
//            objs[0] = patientInfo.getPatientName();
//            objs[1] = patientInfo.getPatientBirthday();
//            objs[2] = patientInfo.getPatientGender();
//            objs[3] = patientInfo.getPatientPhone();
//            objs[4] = patientInfo.getPatientHeight();
//            objs[5] = patientInfo.getPatientBodyWeight();
//            objs[6] = patientInfo.getPatientAddress();
//            objs[7] = patientInfo.getPatientDesc();
//            objs[8] = patientInfo.getCreateTime();
//            dataList.add(objs);
//        }
//        String fileName = "患者列表";
//
//        //执行导出
//        ExcelTool.commonExportExcel(request,response,fileName, rowsName, dataList, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 导出病例列表
     *
     * @param request
     * @param response
     * @param params
     */
    @Override
    public void exportTreatmentList(HttpServletRequest request, HttpServletResponse response, Map<String, Object> params) {

        SysUserInfo userInfo = (SysUserInfo) request.getSession().getAttribute(HttpUtils.CURRENT_USER_4_POJO);

        //校验当前用户是否有全部门店
        boolean isExport = false, isAll = false;
        if(ObjUtils.isNotEmpty(userInfo.getUserId())){
            SysUserInfo sysUserInfo = sysUserInfoMapper.selectByPrimaryKey(userInfo.getUserId());
            List<Map<String,Object>> userFunctionList= roleInfoMapper.selectRoleLists(sysUserInfo.getUserRole());

            List<String> groupList = new ArrayList<>();

            for (Map<String,Object> functionMap : userFunctionList){
                groupList.add(functionMap.get("menuName").toString());
                if(Integer.parseInt(functionMap.get("functionId").toString()) == 14){
                    isExport = true;
                }
                if(Integer.parseInt(functionMap.get("functionId").toString()) == 45){
                    isAll = true;
                }
            }
        }
        //Integer subclinicId = Integer.parseInt(params.get("subclinicId").toString());
        if(isExport) {
            if(ObjUtils.isEmpty(params.get("subclinicId"))){
                if(isAll){
                    params.put("subclinicId", null);
                }else{
                    params.put("subclinicId", params.get("subclinicId"));
                }
            }

            List<Map<String,Object>> treatmentList = patientTreatmentMapper.selectTreatmentList(params);


            //                {"接诊时间","患者姓名","出生年月","性别","手机号","接诊类型","诊所名称","接诊医生","诊断结论",
            //                "发病时间","主诉","主症描述","主症程度","兼症描述","兼症程度","穴位","部位","治疗意见","备注",
            //                "过敏史","家族史","现病史","实验室辅助检查","个人史","疫苗接种历史"};
            //加密
            View m_view = new View();
            try {
                m_view.setTextAsValue(0, 0, "接诊时间");
                m_view.setTextAsValue(0, 1, "患者姓名");
                m_view.setTextAsValue(0, 2, "出生年月");
                m_view.setTextAsValue(0, 3, "性别");
                m_view.setTextAsValue(0, 4, "手机号");
//                m_view.setTextAsValue(0, 5, "接诊类型");
                m_view.setTextAsValue(0, 5, "诊所名称");
                m_view.setTextAsValue(0, 6, "接诊医生");
                m_view.setTextAsValue(0, 7, "诊断结论");
                m_view.setTextAsValue(0, 8, "发病时间");
                m_view.setTextAsValue(0, 9, "主诉");
                m_view.setTextAsValue(0, 10, "主症");
//                m_view.setTextAsValue(0, 12, "主症程度");
                m_view.setTextAsValue(0, 11, "兼症");
//                m_view.setTextAsValue(0, 14, "兼症程度");
                m_view.setTextAsValue(0, 12, "穴位");
//                m_view.setTextAsValue(0, 16, "部位");
                m_view.setTextAsValue(0, 13, "治疗意见");
                m_view.setTextAsValue(0, 14, "备注");
                m_view.setTextAsValue(0, 15, "过敏史");
                m_view.setTextAsValue(0, 16,"家族史");
                m_view.setTextAsValue(0, 17, "现病史");
                m_view.setTextAsValue(0, 18, "实验室辅助检查");
                m_view.setTextAsValue(0, 19, "个人史");
                m_view.setTextAsValue(0, 20, "疫苗接种历史");
                m_view.setTextAsValue(0, 21, "服务类型");
                m_view.setTextAsValue(0, 22, "调理类型");


                for(int j = 1; j <= treatmentList.size() ; j++){
                    m_view.setText(j, 0, String.valueOf(treatmentList.get(j - 1).get("bookingTime")));
                    m_view.setText(j, 1, String.valueOf(treatmentList.get(j - 1).get("patientName")));
                    m_view.setText(j, 2, String.valueOf(treatmentList.get(j - 1).get("patientBirthday")));
                    m_view.setText(j, 3, String.valueOf(treatmentList.get(j - 1).get("patientGender")));
                    m_view.setText(j, 4, String.valueOf(treatmentList.get(j - 1).get("userPhone")));
//                        m_view.setText(j, 5, String.valueOf(treatmentList.get(j - 1).get("isFirst")));
                    m_view.setText(j, 5, String.valueOf(treatmentList.get(j - 1).get("subclinicName")));
                    m_view.setText(j, 6, String.valueOf(treatmentList.get(j - 1).get("doctorName")));
                    m_view.setText(j, 7, String.valueOf(treatmentList.get(j - 1).get("conclusionName")));
                    m_view.setText(j, 8, String.valueOf(treatmentList.get(j - 1).get("diseaseTime")));
                    m_view.setText(j, 9, String.valueOf(treatmentList.get(j - 1).get("diseaseInfo")));
//                        m_view.setText(j, 11, String.valueOf(treatmentList.get(j - 1).get("diseaseType1")));
                    m_view.setText(j, 10, String.valueOf(treatmentList.get(j - 1).get("diseaseName1")));
//                        m_view.setText(j, 13, String.valueOf(treatmentList.get(j - 1).get("diseaseType2")));
                    m_view.setText(j, 11, String.valueOf(treatmentList.get(j - 1).get("diseaseName2")));
                    m_view.setText(j, 12, String.valueOf(treatmentList.get(j - 1).get("pointName")));
//                        m_view.setText(j, 16, String.valueOf(treatmentList.get(j - 1).get("pointType")));
                    m_view.setText(j, 13, String.valueOf(treatmentList.get(j - 1).get("treatmentOpinion")));
                    m_view.setText(j, 14, String.valueOf(treatmentList.get(j - 1).get("treatmentRemarks")));
                    m_view.setText(j, 15, String.valueOf(treatmentList.get(j - 1).get("allergyHistory")));
                    m_view.setText(j, 16, String.valueOf(treatmentList.get(j - 1).get("familyHistory")));
                    m_view.setText(j, 17, String.valueOf(treatmentList.get(j - 1).get("justNowHistory")));
                    m_view.setText(j, 18, String.valueOf(treatmentList.get(j - 1).get("laboratoryHistory")));
                    m_view.setText(j, 19, String.valueOf(treatmentList.get(j - 1).get("userHistory")));
                    m_view.setText(j, 20, String.valueOf(treatmentList.get(j - 1).get("vaccineHistory")));
                    m_view.setText(j, 21, String.valueOf(treatmentList.get(j - 1).get("bookingType")));
                    if(!String.valueOf(treatmentList.get(j - 1).get("bookingType")).equals("预防保健")){
                        m_view.setText(j, 22, String.valueOf(treatmentList.get(j - 1).get("isAdd")));
                    }else{
                        m_view.setText(j, 22, String.valueOf(" "));
                    }
                }

                try{
                    m_view.write("/usr/local/tomcat-test/admin-tomcat/webapps/image/病例信息表.xls","Gyt12345.");
//                    m_view.write("/Users/pingping/workspace/病例信息表.xls");
                }catch (Exception e){
                    e.printStackTrace();
                }
                ExcelTool.download("/usr/local/tomcat-test/admin-tomcat/webapps/image/病例信息表.xls", response);
//                ExcelTool.download("/Users/pingping/workspace/病例信息表.xls", response);
            } catch (CellException e) {
                e.printStackTrace();
            }
        }


//      非加密
//        String[] rowsName = new String[] {
//                "接诊时间","患者姓名","出生年月","性别","手机号","接诊类型","诊所名称","接诊医生","诊断结论",
//                "发病时间","主诉","主症描述","主症程度","兼症描述","兼症程度","穴位","部位","治疗意见","备注",
//                "过敏史","家族史","现病史","实验室辅助检查","个人史","疫苗接种历史"};
//        List<Object[]> dataList = new ArrayList<Object[]>();
//
//        if(treatmentList.size() > 0 ){
//            for (int i = 0 ; i < treatmentList.size() ;i++){
//                //接诊时间
//                Object bookingTime = treatmentList.get(i).get("bookingTime");
//                //患者姓名
//                Object patientName = treatmentList.get(i).get("patientName");
//                //出生年月
//                Object patientBirthday = treatmentList.get(i).get("patientBirthday");
//                //性别
//                Object patientGender = treatmentList.get(i).get("patientGender");
//                //手机号
//                Object userPhone = treatmentList.get(i).get("userPhone");
//                //接诊类型
//                Object isFirst = treatmentList.get(i).get("isFirst");
//                //诊所名称
//                Object subclinicName = treatmentList.get(i).get("subclinicName");
//                //接诊医生
//                Object doctorName = treatmentList.get(i).get("doctorName");
//                //诊断结论
//                Object conclusionName = treatmentList.get(i).get("conclusionName");
//                //主诉
//                Object diseaseInfo = treatmentList.get(i).get("diseaseInfo");
//                //发病时间
//                Object diseaseTime = treatmentList.get(i).get("diseaseTime");
//                //主症描述
//                Object diseaseType1 = treatmentList.get(i).get("diseaseType1");
//                //主症程度
//                Object diseaseName1 = treatmentList.get(i).get("diseaseName1");
//                //兼症描述
//                Object diseaseType2 = treatmentList.get(i).get("diseaseType2");
//                //兼症程度
//                Object diseaseName2 = treatmentList.get(i).get("diseaseName2");
//                //治疗意见
//                Object treatmentOpinion = treatmentList.get(i).get("treatmentOpinion");
//                //穴位
//                Object pointType = treatmentList.get(i).get("pointType");
//                //部位
//                Object pointName = treatmentList.get(i).get("pointName");
//                //备注
//                Object treatmentRemarks = treatmentList.get(i).get("treatmentRemarks");
//                //过敏史
//                Object allergyHistory = treatmentList.get(i).get("allergyHistory");
//                //家族史
//                Object familyHistory = treatmentList.get(i).get("familyHistory");
//                //现病史
//                Object justNowHistory = treatmentList.get(i).get("justNowHistory");
//                //实验室辅助检查
//                Object laboratoryHistory = treatmentList.get(i).get("laboratoryHistory");
//                //个人史
//                Object userHistory = treatmentList.get(i).get("userHistory");
//                //疫苗接种历史
//                Object vaccineHistory = treatmentList.get(i).get("vaccineHistory");
//                Object[] objs = new Object[rowsName.length];
//                objs[0] = bookingTime;
//                objs[1] = patientName;
//                objs[2] = patientBirthday;
//                objs[3] = patientGender;
//                objs[4] = userPhone;
//                objs[5] = isFirst;
//                objs[6] = subclinicName;
//                objs[7] = doctorName;
//                objs[8] = conclusionName;
//                objs[9] = diseaseInfo;
//                objs[10] = diseaseTime;
//                objs[11] = diseaseType1;
//                objs[12] = diseaseName1;
//                objs[13] = diseaseType2;
//                objs[14] = diseaseName2;
//                objs[15] = treatmentOpinion;
//                objs[16] = pointType;
//                objs[17] = pointName;
//                objs[18] = treatmentRemarks;
//                objs[19] = allergyHistory;
//                objs[20] = familyHistory;
//                objs[21] = justNowHistory;
//                objs[22] = laboratoryHistory;
//                objs[23] = userHistory;
//                objs[24] = vaccineHistory;
//                dataList.add(objs);
//            }
//            String fileName = "病例列表";
//
//            //执行导出
            //ExcelTool.commonExportExcel(request,response,fileName, rowsName, dataList, "yyyy-MM-dd HH:mm:ss");

//        }


    }

    @Override
    public void exportOrderList(HttpServletRequest request, HttpServletResponse response, Map<String, Object> params) {

        List<Map<String,Object>> goodsLists = (List<Map<String,Object>>)params.get("goodList");
        Integer ifMonth = (Integer)params.get("ifMonth");
        String orderTime = (String)params.get("orderTime");
        String orderTimeStr = 1 == ifMonth ? orderTime.substring(0, orderTime.length() - 3) : orderTime;
        //加密
        View m_view = new View();
        try {
            m_view.setTextAsValue(0, 0, "销售年月");
            m_view.setTextAsValue(0, 1, "商品名称");
            m_view.setTextAsValue(0, 2, "销售数量");

            for (int j = 1; j <= goodsLists.size(); j++) {
                m_view.setText(j, 0, orderTimeStr);
                m_view.setText(j, 1, String.valueOf(goodsLists.get(j - 1).get("goodsName")));
                m_view.setText(j, 2, String.valueOf(goodsLists.get(j - 1).get("goodsNumber")));
            }

            m_view.setTextAsValue(goodsLists.size() + 1, 0, "消耗总数");
            m_view.setTextAsValue(goodsLists.size() + 1, 1, String.valueOf(params.get("total")));
            m_view.setTextAsValue(goodsLists.size() + 1, 2, "消耗总类");
            m_view.setTextAsValue(goodsLists.size() + 1, 3, String.valueOf(params.get("totalType")));

            try{
                m_view.write("/usr/local/tomcat-test/admin-tomcat/webapps/image/商品销售统计表.xls","Gyt12345.");
//                m_view.write("/Users/pingping/workspace/商品销售统计表.xls");
            }catch (Exception e){
                e.printStackTrace();
            }
            ExcelTool.download("/usr/local/tomcat-test/admin-tomcat/webapps/image/商品销售统计表.xls", response);
//            ExcelTool.download("/Users/pingping/workspace/商品销售统计表.xls", response);
        } catch (CellException e) {
            e.printStackTrace();
        }

    }

    /**
     * 导入会员信息
     *
     * @param excelFile
     * @param request
     * @param response
     * @param params
     */
    @Override
    public void importUserExcel(MultipartFile excelFile, HttpServletRequest request, HttpServletResponse response, Map<String, Object> params) {

        //声明默认返回信息
        String resultMsg = CodeEnum.CODE_60001.getMessage();

        //读取Excel数据
        Map<Integer,Object> excels = new ExcelTool().readExcel(excelFile);

        //如果返回结果不为空
        if(ObjUtils.isNotEmpty(excels)) {
            //获取会员信息
            Object[][] userInfo = (Object[][]) excels.get(0);

            if(ObjUtils.isNotEmpty(userInfo)){
                for (int i = 3; i < userInfo.length; i++) {
                    Integer userId = 0;
                    //创建B端对象
                    TUserInfo userB = new TUserInfo();
                    if(ObjUtils.isNotEmpty(userInfo[i][0]) || ObjUtils.isNotEmpty(userInfo[i][1])){
                        if(ObjUtils.isNotEmpty(userInfo[i][0])){
                            userB.setUserName( userInfo[i][0].toString());
                        }
                        if(ObjUtils.isNotEmpty(userInfo[i][1])){
                            userB.setUserPhone( userInfo[i][1].toString());
                        }
                        if(ObjUtils.isNotEmpty(userInfo[i][2])){
                            userB.setUserBirthday(userInfo[i][2].toString());
                        }
                        if(ObjUtils.isNotEmpty(userInfo[i][3])){
                            userB.setUserGender(Integer.parseInt(userInfo[i][3].toString()));
                        }
                        if(ObjUtils.isNotEmpty(userInfo[i][4])){
                            userB.setUserAccount(new BigDecimal(userInfo[i][4].toString()));
                        }
                        if(ObjUtils.isNotEmpty(userInfo[i][5])){
                            userB.setSubclinicId(Integer.parseInt(userInfo[i][5].toString()));
                        }
                        //默认密码 123456
                        //userB.setUserPwd(MD5Utils.md5Password(SysConstant.userPwd));

                        //通过电话号获取DB中数据
                        params.put("userPhone", userB.getUserPhone());
                        List<TUserInfo> DBuserInfoB = userInfoMapper.selectByMap(params);
                        //如果DB中信息存在
                        if(DBuserInfoB.size() > 0){

                            if( !DBuserInfoB.get(0).getUserName().equals(userB.getUserName()) ){
                                BigDecimal userAccount = new BigDecimal(0);
                                userAccount = userAccount.add(DBuserInfoB.get(0).getUserAccount()).add(userB.getUserAccount());


                                //插入余额流水表
                                AccountUserInfo accountUserInfo = new AccountUserInfo();
                                accountUserInfo.setCashierId(1); // 超级管理员
                                //类型：0:消费;1:充值;
                                accountUserInfo.setAccountType(1);
                                //类型：0:余额;1:次卡;2:储值
                                accountUserInfo.setCardType(0);
                                accountUserInfo.setSubclinicId(userB.getSubclinicId());
                                accountUserInfo.setUserId(DBuserInfoB.get(0).getUserId());
                                accountUserInfo.setAccountCost(userB.getUserAccount());
                                accountUserInfo.setAccountDesc("导入丁香云余额");
                                accountUserInfo.setCreateTime(new Date());
                                accountUserInfo.setBalancePayCost(userB.getUserAccount());
                                accountUserInfo.setDoctorId(1); // 超级管理员
                                //支付方式:0:余额;1:支付宝二维码;2:微信二维码;3:现金;4:信用卡;5:次卡
                                accountUserInfo.setPayWay(0);
                                accountUserInfo.setAccountNo(ObjUtils.getAccountNo());
                                accountUserInfoMapper.insertSelective(accountUserInfo);

                                userB.setUserAccount(userAccount);
                                userB.setUserId(DBuserInfoB.get(0).getUserId());

                                TPatientInfo patient = new TPatientInfo();
                                TPatientInit patientInit = new TPatientInit();

                                patient.setPatientName(userB.getUserName());
                                patient.setPatientGender(userB.getUserGender());
                                if(ObjUtils.isNotEmpty(userB.getUserBirthday())){
                                    try {
                                        Date date = DateUtils.parse(userB.getUserBirthday(),DateUtils.YYYY_MM_DD);
                                        patient.setPatientAge(DateUtils.getAge(date));
                                        patientInit.setUserAge(DateUtils.getAge(date));
                                    }catch (Exception e){
                                        e.printStackTrace();
                                    }
                                }
                                patient.setPatientBirthday(userB.getUserBirthday());
                                patientInit.setUserBirthday(userB.getUserBirthday());
                                patientInit.setUserName(userB.getUserName());
                                patientInit.setUserGender(userB.getUserGender());

                                patient.setUserId(userB.getUserId());

                                patientInfoMapper.insertSelective(patient);

                                patientInit.setPatientId(patient.getPatientId());

                                patientInitMapper.insertSelective(patientInit);

                            }else{
                                //执行修改操作
                                userB.setUserId(DBuserInfoB.get(0).getUserId());
                            }
                            userInfoMapper.updateByPrimaryKeySelective(userB);
                        }else{
                            //如果不存在，执行插入操作
                            if(ObjUtils.isNotEmpty(userB.getUserPhone()) || ObjUtils.isNotEmpty(userB.getUserName())){
                                userInfoMapper.insertSelective(userB);

                                //插入余额流水表
                                AccountUserInfo accountUserInfo = new AccountUserInfo();
                                accountUserInfo.setCashierId(1); // 超级管理员
                                //类型：0:消费;1:充值;
                                accountUserInfo.setAccountType(1);
                                //类型：0:余额;1:次卡;2:储值
                                accountUserInfo.setCardType(0);
                                accountUserInfo.setSubclinicId(userB.getSubclinicId());
                                accountUserInfo.setUserId(userB.getUserId());
                                accountUserInfo.setAccountCost(userB.getUserAccount());
                                accountUserInfo.setAccountDesc("导入丁香云余额");
                                accountUserInfo.setCreateTime(new Date());
                                accountUserInfo.setBalancePayCost(userB.getUserAccount());
                                accountUserInfo.setDoctorId(1); // 超级管理员
                                //支付方式:0:余额;1:支付宝二维码;2:微信二维码;3:现金;4:信用卡;5:次卡
                                accountUserInfo.setPayWay(0);
                                accountUserInfo.setAccountNo(ObjUtils.getAccountNo());
                                accountUserInfoMapper.insertSelective(accountUserInfo);

                                TPatientInfo patient = new TPatientInfo();
                                TPatientInit patientInit = new TPatientInit();

                                patient.setPatientName(userB.getUserName());
                                patient.setPatientGender(userB.getUserGender());
                                if(ObjUtils.isNotEmpty(userB.getUserBirthday())){
                                    try {
                                        Date date = DateUtils.parse(userB.getUserBirthday(),DateUtils.YYYY_MM_DD);
                                        patient.setPatientAge(DateUtils.getAge(date));
                                        patientInit.setUserAge(DateUtils.getAge(date));
                                    }catch (Exception e){
                                        e.printStackTrace();
                                    }
                                }
                                patient.setPatientBirthday(userB.getUserBirthday());
                                patientInit.setUserBirthday(userB.getUserBirthday());
                                patientInit.setUserName(userB.getUserName());
                                patientInit.setUserGender(userB.getUserGender());

                                patient.setUserId(userB.getUserId());

                                patientInfoMapper.insertSelective(patient);

                                patientInit.setPatientId(patient.getPatientId());

                                patientInitMapper.insertSelective(patientInit);
                            }
                        }


                    }
                }
            }
        }
    }
    /**
     * 导入患者信息
     *
     * @param excelFile
     * @param request
     * @param response
     * @param params
     */
    @Override
    public void importPatientExcel(MultipartFile excelFile, HttpServletRequest request, HttpServletResponse response, Map<String, Object> params) {

        //读取Excel数据
        Map<Integer,Object> excels = new ExcelTool().readExcel(excelFile);

        //如果返回结果不为空
        if(ObjUtils.isNotEmpty(excels)) {
            //获取会员信息
            Object[][] patientInfo = (Object[][]) excels.get(0);

            if(ObjUtils.isNotEmpty(patientInfo)){
                for (int i = 0; i < patientInfo.length; i++) {
                    TPatientInfo patient = new TPatientInfo();
                    TPatientInit patientInit = new TPatientInit();
                    if(ObjUtils.isNotEmpty(patientInfo[i][0])){
                        patient.setPatientName( patientInfo[i][0].toString());
                        patientInit.setUserName(patientInfo[i][0].toString());
                    }
                    if(ObjUtils.isNotEmpty(patientInfo[i][1])){
                        patient.setPatientBirthday( patientInfo[i][1].toString());
                        patientInit.setUserBirthday(patientInfo[i][1].toString());
                    }
                    if(ObjUtils.isNotEmpty(patientInfo[i][2])){
                        patient.setPatientGender( Integer.parseInt(patientInfo[i][2].toString()));
                        patientInit.setUserGender( Integer.parseInt(patientInfo[i][2].toString()));
                    }
                    if(ObjUtils.isNotEmpty(patientInfo[i][3])){
                        patient.setPatientDesc( patientInfo[i][3].toString());
                        patientInit.setUserDesc( patientInfo[i][3].toString());
                    }
                    if(ObjUtils.isNotEmpty(patientInfo[i][14])){
                        patient.setPatientCard( patientInfo[i][14].toString());
                    }
                    //通过电话号获取DB中数据
                    params.put("patientDesc", patient.getPatientDesc());
                    List<TPatientInfo> patientList = patientInfoMapper.selectByMap(params);
                    //如果DB中信息存在
                    if(patientList.size() > 0){
                        //执行修改操作
                        patient.setPatientId(patientList.get(0).getPatientId());
                        patientInfoMapper.updateByPrimaryKeySelective(patient);
                    }else{
                        //如果不存在，执行插入操作
                        patientInfoMapper.insertSelective(patient);
                    }
                }
            }
        }

    }


    /**
	* @Title: getFilePath 
	* @Description: 获取文件存储路径
	* @param @param request
	* @param @param path
	* @param @return    
	* @return String     
	* @throws
	 */
	private String getFilePath(HttpServletRequest request, String path){
		// 项目本地根目录
		//req.getSession().getServletContext().getRealPath("/") = "E:\tomcat-out\HunParUpload\webapps\HunParUpload\"
		String filePath = request.getSession().getServletContext().getRealPath("/").replace("\\", "/");
		
		//返回当前文件存储路径
		return filePath.substring(0, filePath.lastIndexOf(request.getContextPath()))+ path;
	}
	
	/**
	* @Title: deleteFile 
	* @Description: 删除文件
	* @param @param filePath
	* @param @return    
	* @return boolean     
	* @throws
	 */
	private boolean deleteFile(String filePath){
		// 如果当前文件路径为空
		if (StringUtils.isEmpty(filePath)) {
			// 返回
			return false;
		}
		// 创建文件对象
		File file = new File(filePath);
		// 如果是存在的
		if (file.exists()) {
			// 删除
			return file.delete();
		}
		return false;
	}


}
